<template>
  <div class="container">
    <!-- 图片展示区域 -->
    <div class="display-area">
      <h3>上传头像</h3>
      <div class="image-container"
          >
        <img v-if="props.smallAvatarUrl" :src="props.smallAvatarUrl" class="display-image" />
        <el-icon v-else class="no-image"><Picture /></el-icon>
      </div>
    </div>

    <!-- 隐藏的文件输入框 -->
    <input
        type="file"
        ref="fileInput"
        style="display: none;"
        @change="handleFileChange"
    />

    <!-- 操作区域 -->
    <div class="action-area">
      <!-- 上传组件 -->

      <!-- 操作按钮 -->
      <div class="button-group">
        <el-button type="primary" @click="handleFileInputClick">
          {{ uploadButtonText }}
        </el-button>
        <el-button type="danger" @click="handleDeleteClick" :disabled="!props.smallAvatarUrl">
          删除图片
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Plus, Picture } from '@element-plus/icons-vue'
  import axios from 'axios'



const props = defineProps({
  smallAvatarUrl: {
    type: String,
    required: true,
  }
})

const emit = defineEmits();

// 文件输入框的引用
const fileInput = ref(null)

// 触发文件选择器
const handleFileInputClick = () => {
  fileInput.value.click() // 触发隐藏的文件输入框
}

const uploadButtonText = computed(() => props.smallAvatarUrl ? '更改图片' : '上传图片')



// 处理文件选择后的变化
const handleFileChange = async (event) => {
  const file = event.target.files[0]
  if (file) {
    // 验证文件类型和大小
    if (!beforeAvatarUpload(file)) return
    // 创建 FormData 对象并添加文件
    const formData = new FormData()
    formData.append('file', file)

    try {
      // 发起上传请求
      const response = await axios.post('http://localhost:8080/upload/images', formData)
      console.log(response.data)
      let respUrl =  response.data.split('/').pop()
      await axios.put(`/user/updateUrl/${respUrl}`)
      emit('update:smallAvatarUrl', response.data+'?'+Math.random());
      ElMessage.success('上传成功')
    } catch (error) {
      ElMessage.error('上传失败：' + (error.message || '未知错误'))
    }
    // 清空文件输入框以允许再次选择相同的文件
    fileInput.value.value = ''
  }
}




  // 上传前的验证
  const beforeAvatarUpload = (file) => {
    const acceptTypes = ['image/jpeg', 'image/png', 'image/gif']
    const isValidType = acceptTypes.includes(file.type)
    const isLt2M = file.size / 1024 / 1024 < 1

    if (!isValidType) {
      ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
      return false
    }
    if (!isLt2M) {
      ElMessage.error('图片大小不能超过 1MB!')
      return false
    }
    return true
  }




  // 处理删除按钮点击
  const handleDeleteClick = async () => {
    try {
      await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      if (props.smallAvatarUrl) {
        let fileName = props.smallAvatarUrl.split('?')[0];
        fileName = fileName.split('/').pop()
        await axios.delete(`http://localhost:8080/upload/delete`, {
          params: { fileName }
        })
        await axios.delete('/user/deleteUrl')
        emit('update:smallAvatarUrl', '');
        ElMessage.success('删除成功')
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除失败：', error)
        ElMessage.error('删除失败：' + (error.message || '未知错误'))
      }
    }
  }

onMounted(() => {

})


</script>

<style scoped>
  .container {
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
  }

  .display-area {
    margin-bottom: 30px;
    text-align: center;
  }

  .image-container {
    width: 300px;
    height: 300px;
    margin: 0 auto;
    border: 2px dashed #dcdfe6;
    border-radius: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
  }

  .display-image {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }

  .no-image {
    font-size: 48px;
    color: #909399;
  }

  .action-area {
    text-align: center;
  }


  .button-group {
    display: flex;
    justify-content: center;
    gap: 16px;
  }
</style>